package com.example.transaction.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.entity.Item;
import com.example.transaction.sys.entity.LoginLog;
import com.example.transaction.sys.entity.User;
import com.example.transaction.sys.service.IItemService;
import com.example.transaction.sys.service.ILoginLogService;
import com.example.transaction.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zh
 * @since 2023-06-20
 */
@RestController
@RequestMapping("/sys/loginLog")
public class LoginLogController {
    @Autowired
    private ILoginLogService loginLogService;

    @Autowired
    private IUserService userService;

    @GetMapping("/all")
    public Result<List<LoginLog>> getAllLoginLog(){
        List<LoginLog> list = loginLogService.list();

        // 获取所有用户ID的列表
        List<Integer> userIds = list.stream()
                .map(LoginLog::getUserID)
                .collect(Collectors.toList());

        // 根据用户ID列表查询对应的用户名
        Map<Integer, String> usernameMap = new HashMap<>();
        for(Integer userid:userIds) {
            String username = userService.getById(userid).getUsername();
            usernameMap.put(userid,username);
        }

        // 设置用户名到每个LoginLog对象中
        for (LoginLog loginLog : list) {
            Integer userId = loginLog.getUserID();
            String username = usernameMap.get(userId);
            loginLog.setUsername(username);
        }

        return Result.success(list, "查询成功");
    }

    /**
     * 新增日志接口
     * @param loginLog
     * @return
     */
    @CacheEvict(value = "loginLogs", allEntries = true)
    @PostMapping("/addLoginLog")
    public Result<?>addLoginLog(@RequestBody LoginLog loginLog){
        try {
            loginLogService.save(loginLog);
        }catch (Exception e){
            return Result.fail("新增失败");
        }
        return Result.success("新增日志成功");
    }

    /**
     * 删除日志
     * @param id
     * @return
     */
    @CacheEvict(value = "loginLogs", allEntries = true)
    @DeleteMapping("/{id}")
    public Result<LoginLog>deleteLoginLogById(@PathVariable("id")Integer id){
        loginLogService.removeById(id);
        return Result.success("删除日志成功");
    }

    /**
     * 查询所有日志，或者按条件查询
     * @param
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
//    @GetMapping("/list")
//    public Result<Map<String,Object>>getLoginLogList(@RequestParam(value = "userName",required = false)String userName,
//                                                 @RequestParam(value = "ip",required = false)String IP,
//                                                     @RequestParam(value = "os",required = false)String OS,
//                                                     @RequestParam(value = "browser",required = false)String browser,
//                                                 @RequestParam(value = "pageNo")Long pageNo,
//                                                 @RequestParam(value = "pageSize")Long pageSize){
//        LambdaQueryWrapper<LoginLog> wrapper=new LambdaQueryWrapper<>();
//        wrapper.like(StringUtils.hasLength(userName),LoginLog::getUsername,userName);
//        wrapper.like(StringUtils.hasLength(IP),LoginLog::getIp,IP);
//        wrapper.like(StringUtils.hasLength(OS),LoginLog::getOs,OS);
//        wrapper.like(StringUtils.hasLength(browser),LoginLog::getBrowser,browser);
//        Page<LoginLog> page=new Page<>(pageNo,pageSize);
//        loginLogService.page(page,wrapper);
//
//
//        List<LoginLog> loginLogList = page.getRecords();
//        List<Integer> userIds = loginLogList.stream()
//                .map(LoginLog::getUserID)
//                .collect(Collectors.toList());
//
//        // 根据用户ID列表查询对应的用户名
//        Map<Integer, String> usernameMap = new HashMap<>();
//        for(Integer userid:userIds) {
//            String username = userService.getById(userid).getUsername();
//            usernameMap.put(userid,username);
//        }
//
//        List<Map<String, Object>> rows = new ArrayList<>();
//        for (LoginLog loginLog : loginLogList) {
//            Map<String, Object> row = new HashMap<>();
//            row.put("loginLogID", loginLog.getLoginLogID());
//            row.put("userID", loginLog.getUserID());
//            row.put("username", usernameMap.get(loginLog.getUserID())); // 添加用户名字段
//            row.put("loginTime", loginLog.getLoginTime());
//            row.put("ip", loginLog.getIp());
//            row.put("os", loginLog.getOs());
//            row.put("browser", loginLog.getBrowser());
//            rows.add(row);
//        }
//        Map<String, Object> data = new HashMap<>();
//        data.put("total", page.getTotal());
//        data.put("rows", rows);
//        return Result.success(data);
//    }
    @GetMapping("/list")
    @Cacheable(value = "loginLogs", key = "'allloginLogs'+#username+#IP+#OS+#browser+#pageNo+#pageSize")
    public Result<Map<String, Object>> getLoginLogList(@RequestParam(value = "username", required = false) String username,
                                                       @RequestParam(value = "ip", required = false) String IP,
                                                       @RequestParam(value = "os", required = false) String OS,
                                                       @RequestParam(value = "browser", required = false) String browser,
                                                       @RequestParam(value = "pageNo") Long pageNo,
                                                       @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(IP), LoginLog::getIp, IP);
        wrapper.like(StringUtils.hasLength(OS), LoginLog::getOs, OS);
        wrapper.like(StringUtils.hasLength(browser), LoginLog::getBrowser, browser);
        wrapper.orderByDesc(LoginLog::getLoginTime);

        if (StringUtils.hasLength(username)) {
            List<Integer> userIds = userService.getUserIdsByUsernameLike(username);
            if (!userIds.isEmpty()) {
                wrapper.in(LoginLog::getUserID, userIds);
            }
            else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }
        Page<LoginLog> page = new Page<>(pageNo, pageSize);
        loginLogService.page(page, wrapper);

        List<LoginLog> loginLogList = page.getRecords();
        List<Map<String, Object>> rows = new ArrayList<>();

        for (LoginLog loginLog : loginLogList) {
            Map<String, Object> row = new HashMap<>();
            row.put("loginLogID", loginLog.getLoginLogID());
            row.put("userID", loginLog.getUserID());
            row.put("username", userService.getById(loginLog.getUserID()).getUsername()); // 添加用户名字段
            row.put("loginTime", loginLog.getLoginTime());
            row.put("ip", loginLog.getIp());
            row.put("os", loginLog.getOs());
            row.put("browser", loginLog.getBrowser());
            rows.add(row);
        }
        // 根据logintime字段排序
        rows.sort(Comparator.comparing(row -> (LocalDateTime) row.get("loginTime")));
        Collections.reverse(rows);
        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", rows);
        return Result.success(data);
    }


    /**
     * 查询传入日期（及前五天）登录的用户,当天有就返回数量，没有就返回0
     * @param date
     * @return
     */
    @Cacheable(value = "loginLogs", key = "'allloginLogs'+#date")
    @GetMapping("/loginNumber")
    public Map<LocalDate, Long> getLoginNumber(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Map<LocalDate, Long> loginNumberByDate = new TreeMap<>();

        for (int i = 0; i < 6; i++) {
            LocalDate currentDate = date.minusDays(i);
            String formattedDate = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            QueryWrapper<LoginLog> loginLogWrapper = new QueryWrapper<>();
            loginLogWrapper.apply("DATE(LoginTime) = {0}", formattedDate);
            Long loginNumber = loginLogService.count(loginLogWrapper);

            loginNumberByDate.put(currentDate, loginNumber);
        }

        return loginNumberByDate;
    }
}
